package com.lyy.common.shiro;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.Set;

@Slf4j
public class JWTRealm extends AuthorizingRealm {

    /**
     * 必须重写此方法，不然Shiro会报错
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JWTToken;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String loginToken = (String) authenticationToken.getCredentials();
        return new SimpleAuthenticationInfo(loginToken, loginToken, "JWTRealm");
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        log.info("JWTRealm>>>>>权限配置");
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
//		String username = JWTUtil.getUsername((String)principals.getPrimaryPrincipal());
//		UserService userService = SpringUtil.getBean(UserService.class);
//		User user = userService.getUserByUsername(username);
//		List<Menu> menus = UserUtil.getMenuRedis(user.getId());
        Set<String> permissions = null;//menus.stream().filter(p -> !StringUtils.isEmpty(p.getPermission())).map(Menu::getPermission).collect(Collectors.toSet());
        authorizationInfo.setStringPermissions(permissions);
        return authorizationInfo;
    }

}